require("../../assets/css/basic.less");
require("../../assets/css/normalize.css");
require("../../assets/css/property.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/font-icon2/iconfont.css");
require("../register/register.less");

const axios = require("axios");
const CaptchaMini = require("captcha-mini");
const eleObj = {};

document.addEventListener("DOMContentLoaded", function () {
	eleObj.phonenumber = document.querySelector("#phonenumber");
	eleObj.password = document.querySelector("#password");
	eleObj.submitBtn = document.querySelector("#submitBtn");
	eleObj.errMsg = document.querySelector(" .text-errMsg ");
	eleObj.checkPassword = document.querySelector(" #checkPassword ");
	eleObj.captcha = document.querySelector(" #captcha ");
	// 验证码
	let code = null;
	//创建验证码
	function disCaptcha() {
		let captcha = new CaptchaMini({
			lineWidth: 1, //线条宽度
			lineNum: 6, //线条数量
			dotR: 2, //点的半径
			dotNum: 25, //点的数量
			preGroundColor: [0, 80], //前景色区间
			backGroundColor: [200, 250], //背景色区间
			fontSize: 80, //字体大小
			fontFamily: ["Georgia", "微软雅黑", "Helvetica", "Arial"], //字体类型
			fontStyle: "fill", //字体绘制方法，有fill和stroke
			content: "abcdefghijklmnopqrstuvwxyz", //验证码内容
			length: 4, //验证码长度
		});
		captcha.draw(document.querySelector("#captchaImg"), function (r) {
			code = r;
		});
	}
	//初始化显示验证码
	disCaptcha();
	let phonenumber = "";
	let password = "";
	eleObj.submitBtn.addEventListener("click", function () {
		// console.log( eleObj.phonenumber,eleObj.password )
		// console.log(weui)
		phonenumber = eleObj.phonenumber.value;
		password = eleObj.password.value;
		const regExp = [
			/^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/, //手机号验证
			/^[a-zA-Z]\w{5,11}$/, //密码验证
		];
		// 判断前端值是否正确
		if (!phonenumber || !regExp[0].test(phonenumber)) {
			eleObj.errMsg.textContent = "手机号格式错误，请重新输入！！";
		} else if (code !== eleObj.captcha.value) {
			eleObj.errMsg.textContent = "验证码输入错误";
		} else if (!password || !regExp[1].test(password)) {
			eleObj.errMsg.textContent = "密码格式错误，必须以字母开头，长度6-12位";
		} else if (password !== eleObj.checkPassword.value) {
			// console.log( eleObj.checkPassword.value )
			eleObj.errMsg.textContent = "两次输入的密码不一致，请重新输入！！";
		} else {
			eleObj.errMsg.textContent = "";
			// 发送异步请求
			axios
				.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
					account: phonenumber,
					password: password,
				})
				.then(function (res) {
					// 请求成功处理
					if (res.data.errno === 0) {
						// 注册成功处理
						location.href = "./login.html";
						alert("恭喜您，账号注册成功！！");
					} else {
						// 注册失败处理
						eleObj.errMsg.textContent = res.data.msg;
					}
				});
		}
	});
});
